package au.edu.jcu.it.numberguess;

import java.util.Date;
import java.util.Random;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class MyFragment extends android.support.v4.app.Fragment {
	private NumberGuessApp app;
	int mCurrentPage = 0;
	private TextView tv;
	protected Button btnYes;
	protected Button btnNo;
	protected TextView tv1;
	protected TextView tv2;
	private AlertDialog alert2, alert3;
	protected CustomViewPager vp;
	private HighScoresOpenHelper highScoresOpenHelper;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		app = (NumberGuessApp) getActivity().getApplication();
		vp = (CustomViewPager) ((GameActivity) getActivity()).getPager();
		highScoresOpenHelper = new HighScoresOpenHelper(getActivity());
		alert2 = new AlertDialog.Builder(getActivity()).create();
		alert3 = new AlertDialog.Builder(getActivity()).create();
		
		/** Getting the arguments to the Bundle object */
		Bundle data = getArguments();

		/** Getting integer data of the key current_page from the bundle */
		mCurrentPage = data.getInt("current_page", 0);

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {

		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.myfragment_layout, container, false);

		tv = (TextView) v.findViewById(R.id.tv);
		tv1 = (TextView) v.findViewById(R.id.tv1);
		tv2 = (TextView) v.findViewById(R.id.tv2);

		if (app.gameSettings.getGameMode().trim().equals("APP GUESS")) {
			btnNo = (Button) v.findViewById(R.id.btnNo);
			btnYes = (Button) v.findViewById(R.id.btnYes);
			btnNo.setVisibility(View.VISIBLE);
			btnYes.setVisibility(View.VISIBLE);

			tv1.setVisibility(View.VISIBLE);
			tv1.setText("IS THERE YOUR SECRECT NUMBER IN THIS CARD?");
			appGuessProcess(v);
		}
		if (app.gameSettings.getGameMode().trim().equals("PLAYER GUESS")) {

			tv1.setVisibility(View.VISIBLE);

			System.out.println("Secrect Number" + app.getAppSecretNumber());
			if (checkSecretNumber(app.cardSamplesModel.get(mCurrentPage - 1)))
				tv1.setText("My secret number IS on this card.");
			else
				tv1.setText("My secret number IS NOT on this card.");

			tv2.setVisibility(View.VISIBLE);
			tv2.setText("What do you think my secrect number is?");
		}

		setUpView();

		return v;
	}

	@SuppressWarnings("deprecation")
	public void showMessageBoxResult(boolean b) {

		alert2.setTitle("Result");
		if (b == true)
			alert2.setMessage("Correct!You win the game!" + "\n"
					+ "Press OK to go home.");
		else
			alert2.setMessage("Wrong!You lose the game!" + "\n"
					+ "Press OK to go home.");

		alert2.setButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent(getActivity()
						.getApplicationContext(), MainActivity.class);
				startActivity(intent);
				getActivity().finish();
			}
		});
		alert2.show();
	}

	public void showMessageBox(int secretNumber) {

		alert3.setTitle("Secret Number !!!");
		alert3.setMessage("Your secret number is " + secretNumber
				+ ". Click YES if the answer is correct, NO otherwise.");
		alert3.setButton(Dialog.BUTTON_POSITIVE,"Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				SQLiteDatabase db = highScoresOpenHelper.getWritableDatabase();
				long numRows = DatabaseUtils.longForQuery(db,
						"SELECT COUNT(*) FROM AppGuess", null) + 1;
				java.text.DateFormat df = java.text.DateFormat
						.getDateTimeInstance();
				String now = df.format(new Date());
				String insertString = String.format("INSERT INTO AppGuess"
						+ "(ID,name,score,datetime)"
						+ "VALUES(\"%s\",\"%s\",\"%s\",\"%s\");",
						Long.toString(numRows), "APP", "WIN", now);
				db.execSQL(insertString);

				getActivity().finish();
			}

		});
		alert3.setButton(Dialog.BUTTON_NEGATIVE, "No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				getActivity().finish();
			}
		});
		app.Refresh();
		alert3.show();
	}

	// app guess function
	public void appGuessProcess(View v) {
		OnClickListener clickListener = new OnClickListener() {
			public void onClick(final View v1) {
				switch (v1.getId()) {
				case R.id.btnNo:
					app.appGuess("NO",
							app.cardSamplesModel.get(mCurrentPage - 1));
					if (app.listGuess.size() <= 2) {
						if (app.listGuess.size() == 1)
							showMessageBox(app.listGuess.get(0));
						else {
							if (app.listGuess.size() == 0)
								showAlert();
							else {
								Random r = new Random();
								int ir;
								showMessageBox(app.listGuess.get(ir = r
										.nextInt(2)));
							}
						}
					}

					if (mCurrentPage <= vp.getAdapter().getCount()) {
						vp.setCurrentItem(mCurrentPage);
					} else {
						Random r = new Random();
						int ir;
						showMessageBox(app.listGuess.get(ir = r
								.nextInt(app.listGuess.size())));
					}

					break;

				case R.id.btnYes:
					app.appGuess("YES",
							app.cardSamplesModel.get(mCurrentPage - 1));
					if (app.listGuess.size() <= 2) {
						Random r = new Random();
						int ir;

						showMessageBox(app.listGuess.get(ir = r.nextInt(1)));
					}

					if (mCurrentPage <= vp.getAdapter().getCount()) {
						vp.setCurrentItem(mCurrentPage);
					} else {
						Random r = new Random();
						int ir;
						showMessageBox(app.listGuess.get(ir = r
								.nextInt(app.listGuess.size() - 1)));
					}
					break;
				}
			}
		};
		btnNo = (Button) v.findViewById(R.id.btnNo);
		btnNo.setOnClickListener(clickListener);
		btnYes = (Button) v.findViewById(R.id.btnYes);
		btnYes.setOnClickListener(clickListener);
	}

	public void showAlert() {
		AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
		alert.setTitle("Alert");
		alert.setMessage("Please do not change your secret number while playing this game!!!");
		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				getActivity().finish();
			}
		});

		alert.show();
	}

	@Override
	public void onDestroy() {
		alert2.dismiss();
		alert3.dismiss();
		super.onDestroy();
	}

	public boolean checkSecretNumber(Card card) {
		int iCheck = -1;
		for (int i = 0; i < card.size(); i++) {
			if (card.get(i) == app.getAppSecretNumber())
				iCheck = 1;
		}
		if (iCheck == -1)
			return false;
		else
			return true;
	}

	public void setUpView() {
		String str;
		// System.out.println("1:" + mCurrentPage);
		if (app.cardSamplesModel.size() >= mCurrentPage) {
			for (int i = 0; i < app.cardSamplesModel.get(mCurrentPage - 1)
					.size(); i++) {
				str = "" + app.cardSamplesModel.get(mCurrentPage - 1).get(i);
				if (app.gameSettings.getRangeNumber() >= 40) {
					if ((i + 1) % 6 == 0)
						str = str + "\n\n\n";
					else
						str = str + "\t\t\t";
				} else {
					if ((i + 1) % 4 == 0)
						str = str + "\n\n\n\n";
					else
						str = str + "\t\t\t";
				}

				tv.append(str);
			}
		}
	}
}
